﻿Imports org.model.lib
Imports IICBusinessLogic.PeriodProcessing

''' <summary>
''' Ticket 156: When a grade is modified on a class member for a period that has already 
''' been processed, we need to allow for re-processing.
''' This is fixed by setting the periodprocessid to null in ClassMember table, 
''' so that the record is picked up by a re-processing operation.
''' The above is done only if the grade is modified from PASS to FAIL, or from FAIL to PASS.
''' </summary>
Public Class GradeChangedValidator
    Implements IModelObjectValidator

    Public Overridable Sub validate(ByVal mo As org.model.lib.Model.IModelObject) _
                Implements org.model.lib.IModelObjectValidator.validate

        Dim c As ClassMember = CType(mo, ClassMember)

        'if period is closed or period is not processed, then just exit
        If c.isFieldChanged(ClassMember.STR_FLD_GRADE) = False Then
            Exit Sub
        End If

        If c.PeriodClass.Period.IsOpen = False Then
            Exit Sub
        End If

        If c.PeriodProcessId IsNot Nothing Then
            'record is already processed...
            Dim passGrade As Integer = c.PeriodClass.PassGrade.GetValueOrDefault

            'grade was changed from fail mark to pass mark
            If c.originalGrade.GetValueOrDefault < passGrade AndAlso _
                 c.Grade.GetValueOrDefault >= passGrade Then

                'set PeriodProcessId to null, so that the record is picked up 
                'in a process period operation
                c.PeriodProcessId = Nothing
                c.gradeChangeNeedsRecalculation = True

            End If

            'grade was changed from a passing mark to fail mark
            If c.originalGrade.GetValueOrDefault >= passGrade AndAlso _
                 c.Grade.GetValueOrDefault < passGrade Then

                'set PeriodProcessId to null, so that the record is picked up 
                'in a process period operation
                Dim sr As New StudentPeriodProcessReverser(c)
                sr.reversePeriodProcess()
                c.PeriodProcessId = Nothing
                c.gradeChangeProcessingWasReversed = True
            End If

        End If

    End Sub

End Class
